package 剑指offer;

public class p52两个链表的第一个公共节点 {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        //齐头并进法
        if (headA==null || headB ==null) {
            return null;//有一个链表为空，那么就没有公共节点
        }

        int lenA=0;
        int lenB=0;
        ListNode nodeA=headA;
        ListNode nodeB=headB;
        while (nodeA!=null) {
            lenA++;
            nodeA=nodeA.next;
        }
        while (nodeB!=null) {
            lenB++;
            nodeB=nodeB.next;
        }

        if (lenA>lenB) {
            for (int i = 0; i <lenA-lenB; i++) {
                headA=headA.next;
            }
        }else if (lenA<lenB) {
            for (int i = 0; i <lenB-lenA; i++) {
                headB=headB.next;
            }
        }


        while (headA!=null) {
            if (headA==headB && headA.next==headB.next) {
                return headA;
            }
            headA=headA.next;
            headB=headB.next;
        }
        return null;
    }
}
